



from DrissionPage import Chromium, ChromiumOptions
import time
from urllib.parse import urlparse, parse_qs
from threading import Thread

def page_info(name):
    start_time = time.time()
    co = ChromiumOptions()
    # co.incognito()  # 匿名模式
    # co.headless()  # 无头模式
    browser = Chromium(co)  # 创建浏览器对象
    browser.set.retry_times(10)  # 设置整体运行参数
    tab = browser.latest_tab  # 获取Tab对象

    # tab.listen.start('/searchNew')  # 开始监听，指定获取包含该文本的数据包
    tab.get(f'https://zhengce.qizhidao.com/overall/all/?keyword={name}&source=home&searchMode=inputSearch')  # 访问网址，这行产生的数据包不监听
    href = tab.ele('.=company-box__header-name') if tab.ele('.=company-box__header-name') else tab.ele('.=companyName')
    # href=tab.ele('xpath://*[@class="company-box__header-name"]')
    href.click()
    time.sleep(1)
    tab = browser.latest_tab
    data = {
        'searchNew': None,
        'getBasicEnterprise': None,
        'getPolicyEnterprise': None,
        'result': None,
        'forCompany': None,
        'towinfo': None,
        'resid': None,
        'success': 0
    }
    tab.listen.start(
        ['/searchNew', '/match/result', '/getBasicEnterprise', '/getPolicyEnterprise', '/checkUrlAccess',
         '/match/forCompany'])
    # TODO:'https://zhengce.qizhidao.com/match/report?companyName=苏州新区高新技术产业股份有限公司&creditCode=9132000025161746XP'
    for packet in tab.listen.steps():
        if time.time() - start_time > 20:
            print("达到超时时间，退出监听。")
            break  # 退出循环

        # print(packet.url)
        print(data.get('success'))
        if '/searchNew' in packet.url and data.get('searchNew') is None:
            data['searchNew'] = packet.response.body
            # print(packet.response.body)  # 打印数据包数据
            data['success'] = data.get('success') + 1
            print(packet.url)
        elif '/match/result' in packet.url and data.get('result') is None and packet.request.method == 'GET':
            parsed_url = urlparse(packet.url)
            query_params = parse_qs(parsed_url.query)
            resid_value = query_params.get('resId', [None])[0]
            data['resid'] = resid_value
            data['result'] = packet.response.body
            # print(packet.response.body)  # 打印数据包数据
            data['success'] = data.get('success') + 1
            print(packet.url)
        elif '/getBasicEnterprise' in packet.url and data.get('getBasicEnterprise') is None:
            data['getBasicEnterprise'] = packet.response.body
            # print(packet.response.body)  # 打印数据包数据
            data['success'] = data.get('success') + 1
            print(packet.url)
        elif '/getPolicyEnterprise' in packet.url and data.get('getPolicyEnterprise') is None:
            data['getPolicyEnterprise'] = packet.response.body
            # print(packet.response.body)  # 打印数据包数据
            data['success'] = data.get('success') + 1
            print(packet.url)
        elif '/match/forCompany' in packet.url and data.get('forCompany') is None:
            data['forCompany'] = packet.response.body
            # print(packet.response.body)  # 打印数据包数据
            data['success'] = data.get('success') + 1
            print(packet.url)
        # TODO:第二深度信息验证
        if data.get('success') == 4 and data.get('resid') and data.get('towinfo') is None:
            print('执行二次网页打开 id:', data.get('resid'))
            data['towinfo'] = True
            tab.get(f'https://zhengce.qizhidao.com/match/{data.get("resid")}.html?hasAnimate=1')
        if data.get('success') >= 5:
            print(f'已完成数据数：{data.get("success")}    退出本次获取')
            break
    # TODO: 检索公司：https://zhengce.qizhidao.com/overall/all/?keyword=苏州新区高新技术产业股份有限公司&source=home&searchMode=inputSearch
    browser.quit()  # 关闭浏览器
    end = time.time()
    print("Total time: {:.3f} seconds".format(end - start_time))
    return data


if __name__ == '__main__':
    name = '星花怒放（苏州）科技有限公司'  # 要查询的公司名
    thread = Thread(target=page_info, args=[name, ])
    thread.start()
    thread.join()
